package com.hzw.code.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 通用自定义异常类
 *
 * @author: 胡汉三
 * @date: 2019/4/1 10:00
 */
public class ActionException extends RuntimeException {
	private static final long serialVersionUID = 3001137375719770241L;

	/**
	 * 错误异常结果
	 */
	private Object result;

	public ActionException() {

	}

	/**
	 * 构造函数
	 *
	 * @param code 响应代码
	 */
	public ActionException(ResultCodeEnum code) {
		super(code.getDesc());
		this.setResult(new ActionResult<>(code));
	}

	/**
	 * 构造函数
	 *
	 * @param code 响应代码
	 * @param msg 业务数据
	 */
	public ActionException(ResultCodeEnum code, String msg) {
		super(StringUtils.isNotBlank(msg) ? msg : code.getDesc());
		this.setResult(new ActionResult(code, msg));
	}

	/**
	 * 构造函数
	 *
	 * @param message 消息提示
	 */
	public ActionException(String message) {
		super(message);
		ActionResult<Object> actionResult = new ActionResult(ResultCodeEnum.ERROR_EXECPTION, message);
		this.result = actionResult;
	}

	/**
	 * 构造函数
	 *
	 * @param code    响应代码
	 * @param msg 消息提示
	 */
	public ActionException(ResultCodeEnum code, String msg, Object data) {
		super(StringUtils.isNotBlank(msg) ? msg : code.getDesc());
		ActionResult<Object> actionResult = new ActionResult(code, msg, data);
		this.result = actionResult;
	}

	/**
	 * 构造函数
	 *
	 * @param result HTTP响应接口输出结果实体
	 */
	public ActionException(ActionResult<Object> result) {
		super(result.getMessage());
		this.result = result;
	}

	public Object getResult() {
		return result;
	}

	public void setResult(ActionResult<Object> result) {
		this.result = result;
	}

	/**
	 * 获取错误堆栈信息
	 *
	 * @return
	 */
	public String getStackTraceString() {
		return getStackTrace(this);
	}

	/**
	 * 获取错误堆栈信息
	 *
	 * @param throwable
	 * @return
	 */
	public static String getStackTrace(Throwable throwable) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		try {
			throwable.printStackTrace(pw);
			return sw.toString();
		} finally {
			pw.close();
		}
	}

	public String toJson() {
		String json = JSONObject.toJSONString(getResult());
		return json;
	}
}
